import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('@/pages/HomePage.vue'),
      meta: {
        title: '首页',
      },
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/pages/user/LoginPage.vue'),
      meta: {
        title: '用户登录',
        hideInMenu: true,
        requiresGuest: true, // 只有未登录用户可以访问
      },
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/pages/user/RegisterPage.vue'),
      meta: {
        title: '用户注册',
        hideInMenu: true,
        requiresGuest: true, // 只有未登录用户可以访问
      },
    },
    {
      path: '/profile',
      name: 'UserProfile',
      component: () => import('@/pages/user/UserProfilePage.vue'),
      meta: {
        title: '个人资料',
        requiresAuth: true, // 需要登录
      },
    },
    {
      path: '/batch-upload',
      name: 'BatchUpload',
      component: () => import('@/pages/admin/PictureBatchUploadPage.vue'),
      meta: {
        title: '批量上传',
        requiresAuth: true, // 需要登录，但不需要管理员权限
      },
    },
    {
      path: '/spaces',
      name: 'SpaceList',
      component: () => import('@/pages/SpaceListPage.vue'),
      meta: {
        title: '我的空间',
        requiresAuth: true, // 需要登录
      },
    },
    {
      path: '/team-spaces',
      name: 'MyTeamSpaces',
      component: () => import('@/pages/MyTeamSpacesPage.vue'),
      meta: {
        title: '我的团队空间',
        requiresAuth: true, // 需要登录
      },
    },
    {
      path: '/spaces/:spaceId/pictures',
      name: 'SpacePictures',
      component: () => import('@/pages/SpacePicturesPage.vue'),
      meta: {
        title: '空间图片',
        requiresAuth: true, // 需要登录
      },
    },
    {
      path: '/spaces/:spaceId/members',
      name: 'SpaceTeamMember',
      component: () => import('@/pages/SpaceTeamMemberPage.vue'),
      meta: {
        title: '团队成员管理',
        requiresAuth: true, // 需要登录
      },
    },
    {
      path: '/admin',
      name: 'Admin',
      redirect: '/admin/users',
      meta: {
        title: '系统管理',
        requiresAuth: true,
        requiresAdmin: true, // 需要管理员权限
      },
    },
    {
      path: '/admin/users',
      name: 'UserManage',
      component: () => import('@/pages/admin/UserManagePage.vue'),
      meta: {
        title: '用户管理',
        requiresAuth: true,
        requiresAdmin: true, // 需要管理员权限
      },
    },
    {
      path: '/admin/pictures/review',
      name: 'PictureReview',
      component: () => import('@/pages/admin/PictureReviewPage.vue'),
      meta: {
        title: '图片审核',
        requiresAuth: true,
        requiresAdmin: true, // 需要管理员权限
      },
    },
    {
      path: '/admin/pictures/batch-upload',
      name: 'PictureBatchUpload',
      component: () => import('@/pages/admin/PictureBatchUploadPage.vue'),
      meta: {
        title: '批量上传',
        requiresAuth: true,
        requiresAdmin: true, // 需要管理员权限
      },
    },
    {
      path: '/admin/spaces',
      name: 'SpaceManage',
      component: () => import('@/pages/admin/SpaceManagePage.vue'),
      meta: {
        title: '空间管理',
        requiresAuth: true,
        requiresAdmin: true, // 需要管理员权限
      },
    },
    {
      path: '/analyze',
      name: 'SpaceAnalyze',
      component: () => import('@/pages/SpaceAnalyzePage.vue'),
      meta: {
        title: '空间分析',
        requiresAuth: true, // 需要登录
      },
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/pages/NotFoundPage.vue'),
      meta: {
        title: '页面不存在',
        hideInMenu: true,
      },
    },
  ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - Han Picture` : 'Han Picture'

  console.log(`路由守卫: 从 ${from.path} 到 ${to.path}`)

  // 如果从localStorage恢复了用户信息，需要验证是否仍然有效
  // 如果没有用户信息，也需要尝试获取
  if (!userStore.loginUser || localStorage.getItem('loginUser')) {
    try {
      await userStore.fetchLoginUser()
    } catch (error: unknown) {
      console.log('获取用户信息失败，可能未登录:', error)
      // 如果获取失败，确保清除本地存储的用户信息
      userStore.clearUser()
    }
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLogin) {
    message.warning('请先登录')
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin && !userStore.isAdmin) {
    message.error('权限不足')
    next({ name: 'Home' })
    return
  }

  // 检查是否只允许未登录用户访问
  if (to.meta.requiresGuest && userStore.isLogin) {
    next({ name: 'Home' })
    return
  }

  next()
})

export default router
